package com.chao.gateway.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.chao.gateway.authorization.AuthorizationManager;
import com.chao.gateway.filter.IgnoreUrlsRemoveJwtFilter;
import com.chao.gateway.handler.RestAuthenticationEntryPoint;
import com.chao.gateway.handler.RestfulAccessDeniedHandler;
import com.chao.gateway.properties.IgnoreUrlsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.reactive.CorsWebFilter;
import reactor.core.publisher.Mono;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/26
 */
@Configuration
@EnableWebFluxSecurity
@Slf4j
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private AuthorizationManager authorizationManager;
    @Autowired
    private IgnoreUrlsProperties ignoreUrlsProperties;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter;
    @Autowired
    private CorsWebFilter corsWebFilter;

    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http){
        http.csrf(ServerHttpSecurity.CsrfSpec::disable)
                .authorizeExchange().pathMatchers(Convert.toStrArray(ignoreUrlsProperties.getWhiteUrls())).permitAll()
                .anyExchange().access(authorizationManager)
                .and()
                .oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter()).jwkSetUri("http://192.168.150.12:19003/rsa/publicKey")
                //没有登录或token过期时
                .and()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
                .addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION)
                .addFilterBefore(corsWebFilter,SecurityWebFiltersOrder.CORS)
                .exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
                //自定义返回结果：没有权限访问时
                .accessDeniedHandler(restfulAccessDeniedHandler);
        return http.build();
    }
}
